import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { parseLocalDate } from '../../utils/date'
import { z } from 'zod'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc.js'
import timezone from 'dayjs/plugin/timezone.js'

dayjs.extend(utc)
dayjs.extend(timezone)

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({ childId: z.string(), start: z.string().optional(), end: z.string().optional(), days: z.string().optional() })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, childId)

  let start: Date
  let end: Date
  if (parsed.data.start && parsed.data.end) {
    start = parseLocalDate(parsed.data.start)
    end = parseLocalDate(parsed.data.end)
  } else {
    const daysCount = Number(parsed.data.days ?? '30')

    // 获取今天的日期（Asia/Shanghai时区）
    const today = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD')

    // 计算N天前的日期
    const startDate = dayjs().tz('Asia/Shanghai').subtract(daysCount - 1, 'day').format('YYYY-MM-DD')

    // 开始时间：N天前的 00:00:00
    start = parseLocalDate(startDate)

    // 结束时间：今天的 23:59:59.999
    end = new Date(parseLocalDate(today).getTime() + 24 * 60 * 60 * 1000 - 1)
  }

  const ledger = await prisma.pointsLedger.findMany({
    where: { childId, occurredAt: { gte: start, lte: end } },
    orderBy: { occurredAt: 'asc' }
  })

  // 计算天数
  const startDate = parseLocalDate(dayjs(start).format('YYYY-MM-DD'))
  const endDate = parseLocalDate(dayjs(end).format('YYYY-MM-DD'))
  const daysCount = Math.floor((endDate.getTime() - startDate.getTime()) / (24*60*60*1000)) + 1

  const series = Array.from({ length: daysCount }, () => 0)
  for (const l of ledger) {
    const ledgerDate = parseLocalDate(dayjs(l.occurredAt).tz('Asia/Shanghai').format('YYYY-MM-DD'))
    const idx = Math.floor((ledgerDate.getTime() - startDate.getTime()) / (24*60*60*1000))
    if (idx >= 0 && idx < daysCount) {
      const v = l.kind === 'earn' ? l.amount : l.kind === 'spend' ? -l.amount : l.amount
      series[idx] += v
    }
  }

  return { start, end, series }
})


